package java0330;

class Node {
    public int key;
    public int value;
    public Node next;

    public Node(int key, int value) {
        this.key = key;
        this.value = value;
    }
}

public class MyHashMap1 {
    private Node[] array = new Node[16];

    private int size = 0;

    private int hash(int key) {
        return key % array.length;
    }

    // 插入
    public void put(int key, int value) {
        int index = hash(key);
        if (array[index] == null) {
            array[index] = new Node(key, value);
            size++;
            return;
        }
        for (Node cur = array[index]; cur != null; cur = cur.next) {
            if (cur.key == key) {
                cur.value = value;
                return;
            }
        }
        Node newNode = new Node(key, value);
        newNode.next = array[index];
        array[index] = newNode;
        size++;
        if (loadFactor() > 0.75) {
            resize();
        }
    }

    // 查找
    public Integer get(int key) {
        int index = hash(key);
        if (array[index] == null) {
            return null;
        }
        for (Node cur = array[index]; cur != null; cur = cur.next) {
            if (cur.key == key) {
                return cur.value;
            }
        }
        return null;
    }

    public Integer remove (int key) {
        int index = hash(key);
        if (array[index] == null) {
            return null;
        }
        Integer ret = null;
        Node pre = null;
        if (array[index].key == key) {
            ret = array[index].value;
            array[index] = array[index].next;
            size--;
            return ret;
        }
        for (Node cur = array[index]; cur != null; pre = cur, cur = cur.next) {
            if (cur.key == key) {
                ret = cur.value;
                pre.next = cur.next;
                size--;
                return ret;
            }
        }
        return null;
    }

    private void resize() {
        Node[] newArray = new Node[2 * array.length];
        for (int index = 0; index < array.length; index++) {
            for (Node cur = array[index]; cur != null; cur = cur.next) {
                int newIndex = cur.key % newArray.length;
                if (newArray[newIndex] == null) {
                    newArray[newIndex] = cur;
                }else {
                    cur.next = newArray[newIndex].next;
                    newArray[newIndex] = cur;
                }
            }
        }
        array = newArray;
    }

    private double loadFactor() {
        return (double) size / array.length;
    }

}
